<template>
  <div>
    <el-upload
      :on-preview="preview"
      :on-remove="handleRemove"
      :on-change="changeFile"
      :file-list="fileList"
      :before-upload="beforeUpload"
      list-type="picture-card"
      action="#"
      :limit="1"
      :class="{disabled: fileComputed }"
      :auto-upload="true"
      :http-request="upload"
    >
      <i class="el-icon-plus" />
      <el-progress v-if="showPercent" style="width: 180px" :percentage="percent" />
    </el-upload>
    <el-dialog title="预览图片" :visible.sync="showDialog" width="30%">
      <img :src="imgUrl" alt="">
    </el-dialog>

  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'

const cos = new COS({
  SecretId: 'AKIDvgBPN5WgaEcjaATVFivrWu2uVpsfCSSC',
  SecretKey: 'UjjSu5zcy3rNdz5uSklW0EBqFOFp8BxS'
})
export default {
  name: 'ImageUpload',
  data() {
    return {
      fileList: [],
      showDialog: false,
      imgUrl: '',
      currentFile: null,
      percent: 0,
      showPercent: false // 默认不显示进度条
    }
  },
  computed: {
    fileComputed() {
      return this.fileList.length === 1
    }
  },
  methods: {
    preview(file) {
      this.imgUrl = file.url
      this.showDialog = true
    },
    changeFile(file, fileList) {
      // this.fileList.push({ name: file.name, url: file.url, uid: file.uid })
      this.fileList = fileList.map(item => item)
    },
    handleRemove(file, fileList) {
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    beforeUpload(file) {
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('上传图片类型不正确!')
        return false
      }
      const maxSize = 5 * 1024 * 1024
      if (maxSize < file.size) {
        this.$message.warning('图片大小最大不能超过5M')
        return false
      }
      this.currentFile = file.uid
      this.showPercent = true
      return true
    },
    upload(params) {
      cos.putObject({
        Bucket: 'chenqing-1308731775', // 存储桶
        Region: 'ap-nanjing', // 地域
        Key: params.file.name, // 文件名
        Body: params.file, // 要上传的文件对象
        StorageClass: 'STANDARD' // 上传的模式类型 直接默认 标准模式即可
        // 上传到腾讯云 =》 哪个存储桶 哪个地域的存储桶 文件  格式  名称 回调
      }, (err, data) => {
        if (err) {
          return this.$message.error('上传出错')
        }
        this.fileList = this.fileList.map(item => {
          if (item.uid === this.currentFile) {
            return { url: 'http://' + data.Location, upload: true }
          }
          return item
        })
        setTimeout(() => {
          this.showPercent = false
        }, 400)
      })
    }
  }
}

</script>

<style scoped lang="scss">
 ::v-deep .disabled {
   .el-upload--picture-card {
     display: none;
   }
 }
</style>
